package com.nft.service.school.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nft.constant.response.ResponseConstants;
import com.nft.po.NftResponse;
import com.nft.service.school.entity.SchoolPatriarchEntity;
import com.nft.service.school.entity.SchoolVisitorEntity;
import com.nft.service.school.entity.SysDeptEntity;
import com.nft.service.school.entity.SysUserEntity;
import com.nft.service.school.mapper.SchoolPatriarchMapper;
import com.nft.service.school.mapper.SchoolVisitorMapper;
import com.nft.service.school.mapper.SysDeptMapper;
import com.nft.service.school.mapper.SysUserMapper;
import com.nft.service.school.req.SysUserReq;
import com.nft.service.school.resp.LoginResp;
import com.nft.service.school.resp.SysDeptResp;
import com.nft.service.school.resp.SysUserResp;
import com.nft.service.school.service.SysUserService;
import com.nft.utils.dateFormat.SimpleDateFormatUtil;
import com.nft.utils.query.QueryUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity> implements SysUserService {
    private static Logger logger = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SchoolPatriarchMapper schoolPatriarchMapper;

    @Autowired
    private SchoolVisitorMapper schoolVisitorMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Override
    public NftResponse<SysUserResp> getUserAppInfoByPhone(String phone) {
        QueryWrapper<SysUserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(QueryUtil.camelToUnderline("status"), "0");
        wrapper.eq(QueryUtil.camelToUnderline("delFlag"), "0");
        wrapper.eq(QueryUtil.camelToUnderline("phonenumber"), phone);
        List<SysUserEntity> users = this.baseMapper.selectList(wrapper);
        if (users==null||users.size()<=0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "查无此人", null);
        }
        SysUserResp userAppResp = BeanUtil.copyProperties(users.get(0), SysUserResp.class);
        SysUserResp rtn = this.baseMapper.getUserStudent(users.get(0).getUserId());
        if (null!=rtn&&null!=rtn.getUserId()) {
            userAppResp.setIsTeacher(true);
        }else {
            userAppResp.setIsTeacher(false);
        }
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "查询成功", userAppResp);
    }

    @Override
    public NftResponse<SysUserResp> getUserAppInfoById(Long userId) {
        SysUserEntity userAppEntity = this.baseMapper.selectById(userId);
        if (userAppEntity == null) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "查无此人", null);
        }
        SysUserResp userAppResp = BeanUtil.copyProperties(userAppEntity, SysUserResp.class);
        SysUserResp rtn = this.baseMapper.getUserStudent(userAppEntity.getUserId());
        if (null!=rtn&&null!=rtn.getUserId()) {
            userAppResp.setIsTeacher(true);
        }else {
            userAppResp.setIsTeacher(false);
        }
        userAppResp.setPhone(userAppResp.getPhonenumber());
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "查询成功", userAppResp);
    }

    private String getXsUserNo(Long deptId) {
        DecimalFormat decimalFormat = new DecimalFormat("000000");
        List xsList = this.baseMapper.selectUserList(deptId, "xuesheng");
        String numFormat = decimalFormat.format(xsList.size()+1);
        return deptId+"xs"+numFormat;
    }

    @Override
    public NftResponse<Boolean> updateUserAppInfo(SysUserReq query) {
        String patriarchName = query.getUserName();
        if (query.getUserId() == null || query.getUserId() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "系统错误", null);
        }
        Object redisLoginInfoObj = redisTemplate.opsForValue().get("userinfo-app:" + query.getUserId());
        if (redisLoginInfoObj == null) {
            return new NftResponse<>(ResponseConstants.TOKEN_CODE, "请重新登录", null);
        }
        LoginResp redisLoginInfo = JSONUtil.toBean(redisLoginInfoObj.toString(), LoginResp.class);
        if (redisLoginInfo == null) {
            return new NftResponse<>(ResponseConstants.TOKEN_CODE, "请重新登录", null);
        }
        if (null!=query.getChildname()&&!"".equals(query.getChildname())) {
            query.setUserName(query.getChildname());
        }
        QueryWrapper<SysDeptEntity> wrapperQueryDept = new QueryWrapper<>();
        wrapperQueryDept.ne(QueryUtil.camelToUnderline("parentId"), "0");
        wrapperQueryDept.eq(QueryUtil.camelToUnderline("status"), "0");
        wrapperQueryDept.eq(QueryUtil.camelToUnderline("deptName"), query.getSchool());
        List<SysDeptEntity> deptList = sysDeptMapper.selectList(wrapperQueryDept);
        List<SysDeptResp> deptResult = BeanUtil.copyToList(deptList, SysDeptResp.class);
        Boolean result = true;
        SysUserResp postXsResp = this.baseMapper.getStudentPostInfo();
        if (null!=deptResult&&deptResult.size()>0) {
            query.setDeptId(deptResult.get(0).getDeptId());
            QueryWrapper<SysUserEntity> wrapper = new QueryWrapper<>();
            wrapper.eq(QueryUtil.camelToUnderline("phonenumber"), redisLoginInfo.getPhone());
            wrapper.eq(QueryUtil.camelToUnderline("deptId"), query.getDeptId());
            wrapper.eq(QueryUtil.camelToUnderline("delFlag"),"0");
            wrapper.eq(QueryUtil.camelToUnderline("status"), "0");
            Long userCount = this.baseMapper.selectCount(wrapper);
            if(userCount > 0) {
                result = updateById(BeanUtil.copyProperties(query, SysUserEntity.class));
            }else {
                SysUserEntity sysUserEntity = new SysUserEntity();
                sysUserEntity.setPhonenumber(redisLoginInfo.getPhone());
                sysUserEntity.setUserName(query.getUserName());
                sysUserEntity.setCreateTime(SimpleDateFormatUtil.getNowDate());
                sysUserEntity.setDeptId(query.getDeptId());
                sysUserEntity.setOpenId(redisLoginInfo.getOpenId());
                String xsNo = this.getXsUserNo(query.getDeptId());
                sysUserEntity.setUserNo(xsNo);
                this.baseMapper.insert(sysUserEntity);

                List<SysUserEntity> userList = this.baseMapper.selectList(wrapper);
                if (null!=userList&&userList.size()>0) {
                    SysUserResp roleXsResp = this.baseMapper.getStudentRoleInfo();
                    this.baseMapper.insertUserPost(userList.get(0).getUserId(), postXsResp.getPostId());
                    this.baseMapper.insertUserRole(userList.get(0).getUserId(), roleXsResp.getRoleId());
                }
            }
        }else {
            result = updateById(BeanUtil.copyProperties(query, SysUserEntity.class));
        }
        QueryWrapper<SysUserEntity> wrapperUser = new QueryWrapper<>();
        wrapperUser.eq(QueryUtil.camelToUnderline("phonenumber"), redisLoginInfo.getPhone());
        wrapperUser.eq(QueryUtil.camelToUnderline("delFlag"),"0");
        wrapperUser.eq(QueryUtil.camelToUnderline("status"), "0");
        List<SysUserEntity> userList = this.baseMapper.selectList(wrapperUser);
        for (SysUserEntity user:userList) {
            if (user.getUserId().longValue()!=query.getUserId().longValue()) {
                user.setUserName(query.getChildname());
                String xsNo = this.getXsUserNo(user.getDeptId());
                user.setUserNo(xsNo);
                updateById(user);
            }
        }
        SysUserResp userpostResp = this.baseMapper.getUserPostInfo(query.getUserId());
        if (null==userpostResp) {
            this.baseMapper.insertUserPost(query.getUserId(), postXsResp.getPostId());
        }
        setParent(patriarchName, redisLoginInfo.getPhone(), query);
        setVisitor(query.getSchool(), patriarchName, redisLoginInfo.getPhone());
        if (!result) {
            return new NftResponse(ResponseConstants.ERROR_CODE, "保存失败", false);
        }
        return new NftResponse(ResponseConstants.SUCCESS_CODE, "保存成功", true);
    }

    private void setParent(String patriarchName, String phone, SysUserReq query) {
        QueryWrapper<SchoolPatriarchEntity> wrapperQueryPat = new QueryWrapper<>();
        wrapperQueryPat.eq(QueryUtil.camelToUnderline("studentId"), query.getUserId());
        List<SchoolPatriarchEntity> listPat = schoolPatriarchMapper.selectList(wrapperQueryPat);
        if (null!=listPat&&listPat.size()>0) {
            SchoolPatriarchEntity entity = listPat.get(0);
            entity.setName(patriarchName);
            entity.setPhone(phone);
            entity.setStudentId(query.getUserId());
            entity.setChildname(query.getChildname());
            entity.setSchoolId(query.getDeptId());
            schoolPatriarchMapper.updateById(entity);
        }else {
            SchoolPatriarchEntity entity = new SchoolPatriarchEntity();
            entity.setName(patriarchName);
            entity.setPhone(phone);
            entity.setStudentId(query.getUserId());
            entity.setChildname(query.getChildname());
            entity.setSchoolId(query.getDeptId());
            entity.setCreateTime(SimpleDateFormatUtil.getNowDate());
            schoolPatriarchMapper.insert(entity);
        }
    }

    private void setVisitor(String school, String patriarchName, String phone) {
        QueryWrapper<SchoolVisitorEntity> wrapperQueryVis = new QueryWrapper<>();
        wrapperQueryVis.eq(QueryUtil.camelToUnderline("phone"), phone);
        List<SchoolVisitorEntity> listVis = schoolVisitorMapper.selectList(wrapperQueryVis);
        if (null!=listVis&&listVis.size()>0) {
            SchoolVisitorEntity entity = listVis.get(0);
            if (null==school||"".equals(school)) {
                entity.setName(patriarchName);
                schoolVisitorMapper.updateById(entity);
            }else {
                schoolVisitorMapper.deleteById(entity);
            }
        }
    }
}
